package group

import (
	"context"
	"database/sql"
	"fmt"
	"github.com/zeromicro/go-zero/core/fx"
	"go-admin/base/dao"
	"go-admin/base/utils"
	"go-admin/base/ws"

	"go-admin/base/internal/svc"
	"go-admin/base/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddGroupsLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAddGroupsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddGroupsLogic {
	return &AddGroupsLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AddGroupsLogic) AddGroups(req *types.UserGroupsSaveReqDTO) (resp *types.GroupBooleanRespDTOS, err error) {
	userGroups, err := l.svcCtx.UserGroupModel.FindByGroupIds(l.ctx, []int64{req.UserId})
	if err != nil {
		_ = fmt.Errorf(err.Error())
		return nil, err
	}
	groupIds := req.GroupIds
	groupIdsDB := utils.Collector[int64](fx.From(func(source chan<- any) {
		for _, group := range userGroups {
			source <- group.GroupId
		}
	}))
	var userGroups1 []*dao.UserGroup
	fx.From(func(source chan<- any) {
		for _, groupId := range groupIds {
			source <- groupId
		}
	}).Filter(func(item any) bool {
		groupId := item.(int64)
		return !utils.IsContain(groupIdsDB, groupId)
	}).ForEach(func(item any) {
		groupId := item.(int64)
		userGroups1 = append(userGroups1, &dao.UserGroup{
			UserId: sql.NullInt64{
				Int64: req.UserId,
				Valid: true,
			},
			GroupId: sql.NullInt64{
				Int64: groupId,
				Valid: true,
			},
		})
	})

	err = l.svcCtx.UserGroupModel.BatchInsert(l.ctx, l.svcCtx.Conn, userGroups1)

	// 聊天服务器需要组中加入用户
	for _, userGroup := range userGroups1 {
		groupId := userGroup.GroupId.Int64
		userId := userGroup.UserId.Int64
		chatRoom := ws.RoomServer.ChatRooms[groupId]
		chatRoom.AddClient(userId)
	}

	return &types.GroupBooleanRespDTOS{
		Data: true,
		Result: types.Result{
			Code: 200,
		},
	}, nil
}
